package com.ruoyi.certificate.wxapi;

import com.ruoyi.certificate.domain.NjtUserRegister;
import com.ruoyi.certificate.domain.UserRegisterRequest;
import com.ruoyi.certificate.service.INjtUserRegisterService;
import com.ruoyi.certificate.utils.SmsUtils;
import com.ruoyi.certificate.utils.ValidateCodeUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/api/user")
public class WxUserApi {
     //创建一个线程安全的map
    private static final java.util.Map<String,String> map=new java.util.HashMap<>();

    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private INjtUserRegisterService iNjtUserRegisterService;
    @GetMapping("/sendValidateCode")
    public String sendValidateCode(String mobilePhone){
        //1.生成6位数验证码，保存到服务器（map）
        String code= ValidateCodeUtils.generateValidateCode(6);

        //将验证码保存到map中(key:手机号 value:验证码)
        map.put(mobilePhone,code);
        System.out.println("验证码："+code);

        //2.调用阿里云短信服务发送验证码
//        smsUtils.sendSms(mobilePhone,code);
        return "success";
    }

    @GetMapping("/checkMobilePhone")
    public AjaxResult checkMobilePhone(String mobilePhone){
       NjtUserRegister njtUserRegister= iNjtUserRegisterService.checkMobilePhone(mobilePhone);
        if (njtUserRegister!=null) {
            return AjaxResult.error(400, "手机号已经注册");
        } else{
            return AjaxResult.success("手机号未注册");
        }
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserRegisterRequest userRegisterRequest){
        System.out.println(userRegisterRequest);
        //1.校验验证码是否正确
        String mobilePhone=userRegisterRequest.getMobilePhone();

        String redisCode=map.get(mobilePhone);
        if (redisCode==null){
            return AjaxResult.error(400,"验证码已过期");
        }
        String checkCode=userRegisterRequest.getCheckCode();
        if (!redisCode.equals(checkCode)){
            return AjaxResult.error(400,"验证码错误");
        }
        iNjtUserRegisterService.register(userRegisterRequest);
        return AjaxResult.success("注册成功");

    }

}
